#!/bin/bash

if [[ $# == 0 ]]; then
	echo "$0 <mod data dir>"
	exit
fi
target_dir=$(echo ~/.wine/drive_c/*/Steam/steamapps/common/Skyrim/Data)
if [[ ! -d $target_dir ]]; then
	echo "Could not find Skyrim data directory."
	exit
fi
source_dir=$1
if [[ ! -d $source_dir ]]; then
	echo "Could not find mod data directory."
	exit
fi

allow_patterns=( "Interface/**"
		 "Meshes/**"
		 "Scripts/source/*.psc"
		 "Scripts/*.pex"
		 "Seq/**"
		 "Skse/**"
		 "Sound/**"
		 "Strings/**"
		 "Textures/**"
		 "Tools/**"
		 "*.bsa"
		 "*.esm"
		 "*.esp"
		 "*.ini" )

find "$source_dir" -printf '%P\n' | sed '/^$/d' | sort | while read source_path; do
	if [[ "$source_path" == */* ]]; then
		toplevel_path=${source_path%%/*}
		sublevel_path=${source_path#*/}
	else
		toplevel_path=$source_path
		sublevel_path=
	fi
	if [[ -d $source_dir/$toplevel_path ]]; then
		toplevel_path=${toplevel_path,,}
		toplevel_path=${toplevel_path^}
	fi
	sublevel_path=${sublevel_path,,}
	if [[ "$source_path" == */* ]]; then
		target_path=$toplevel_path/$sublevel_path
	else
		target_path=$toplevel_path
	fi
	
	process_this=
	for allow_pattern in "${allow_patterns[@]}"; do
		if [[ "$allow_pattern" == */* ]]; then
			if [[ "$target_path" == $allow_pattern ]]; then
				process_this=y
			fi
			allow_pattern=$(dirname $allow_pattern)
			if [[ "$target_path" == $allow_pattern ]]; then
				process_this=y
			fi
		else
			if [[ "$target_path" == $allow_pattern &&
			      "$target_path" != */* ]]; then
				process_this=y
			fi
		fi
	done
	
	if [[ $process_this != "" ]]; then
		if [[ -d $source_dir/$source_path ]]; then
			if [[ ! -d $target_dir/$target_path ]]; then
				mkdir "$target_dir/$target_path"
			fi
		fi
		if [[ -f $source_dir/$source_path ]]; then
			cp "$source_dir/$source_path" "$target_dir/$target_path"
		fi
		echo "copied $source_path"
	else
		echo "ignored $source_path"
	fi
done
